#include <bits/stdc++.h>

using namespace std;

class Solution
{
public:
    int numOfMinutes(int n, int headID, vector<int> &manager, vector<int> &informTime)
    {
        int ret = 0;
        vector<vector<int>> g(n);
        for (int i = 0; i < n; ++i)
        {
            if (manager[i] >= 0)
            {
                g[manager[i]].push_back(i);
            }
        }
        function<int(int)> dfs = [&](int x) -> int
        {
            int maxPathSum = 0;
            for (int y : g[x])
            {
                maxPathSum = max(maxPathSum, dfs(y));
            }
            return maxPathSum + informTime[x];
        };
        return dfs(headID);
    }
};